package com.ktjiaoyu.crm.web.controller;

import com.ktjiaoyu.crm.entity.Customer;
import com.ktjiaoyu.crm.entity.User;
import com.ktjiaoyu.crm.service.ICustomerService;
import com.ktjiaoyu.crm.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 控制器---客户
 * @author lee
 */
@Controller
public class CustomerController {
    @Resource
    private ICustomerService customerService;

    @Resource
    private IUserService userService;

    @RequestMapping(value = "/cust/list")
    public String list(String custName, String custNo, String custRegion, String custManagerName, Integer custLevel,
                       Model model, HttpSession session,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex) {
        Pageable pageable = PageRequest.of(pageIndex - 1, 5);
        User loginUser = (User) session.getAttribute("loginUser");
        Page<Customer> customerPage = null;

        //判断当前用户是否是客户经理
        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("客户经理")) {
            customerPage = customerService.findCustomers(custName, custNo, custRegion, loginUser.getUsrName(), custLevel, pageable);
        } else if (subject.hasRole("营销主管")) {
            customerPage = customerService.findCustomers(custName, custNo, custRegion, custManagerName, custLevel, pageable);
        }

        model.addAttribute("custName", custName);
        model.addAttribute("custNo", custNo);
        model.addAttribute("custRegion", custRegion);
        model.addAttribute("custManagerName", custManagerName);
        model.addAttribute("custLevel", custLevel);
        model.addAttribute("customerPage", customerPage);
        return "cust/list";
    }

    @RequestMapping(value = "/cust/add")
    public String add(Model model) {
        return "cust/add";
    }

    @RequestMapping(value = "/cust/json")
    @ResponseBody
    public List<User> findCustomerManager(Long roleId) {
        List<User> list = customerService.findUserByRoleId(2L);
        return list;
    }
}
